<template>
  <div class="game-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="小游戏" left-arrow @click-left="onClickLeft" fixed placeholder>
      <template #right>
        <van-icon name="search" @click="handleSearch" />
        <van-icon name="bell-o" @click="handleNotification" class="ml-4" />
      </template>
    </van-nav-bar>

    <!-- 主内容区域 -->
    <div class="page-content">
      <!-- 小游戏内容区域 -->
      <div class="game-section">
        <h2 class="game-title">普通话发音小游戏</h2>

        <div class="game-container">
          <!-- 游戏图片 -->
          <div class="game-image-container">
            <van-image :src="currentGame?.image || defaultGameData[0].image" alt="游戏图片" class="game-image" fit="cover" round />

            <!-- 拼音显示 -->
            <p class="game-pinyin">{{ currentGame?.pinyin || defaultGameData[0].pinyin }}</p>
          </div>

          <!-- 录音按钮 -->
          <van-button :class="['record-button', { recording: isRecording }]" @click="toggleRecording" round size="large">
            <van-icon :name="isRecording ? 'pause' : 'play'" :class="['microphone-icon', { recording: isRecording }]" size="32" />
          </van-button>

          <!-- 录音状态 -->
          <p class="record-status">{{ recordStatus }}</p>
        </div>

        <!-- 结果显示区域 -->
        <div class="result-card" v-if="showResult">
          <div class="result-title">
            <van-icon name="volume-o" class="title-icon" />
            发音结果
          </div>
          <div class="result-content">
            <div class="result-item">
              <span class="result-label">您的发音：</span>
              <span class="result-value">{{ gameResult.userPronunciation }}</span>
            </div>
            <div class="result-item">
              <span class="result-label">标准发音：</span>
              <span class="result-value">{{ gameResult.standardPronunciation }}</span>
            </div>
            <div class="result-item">
              <span class="result-label">相似度：</span>
              <span class="result-value similarity">{{ gameResult.similarity }}%</span>
            </div>
            <div class="result-item">
              <span class="result-label">得分：</span>
              <span :class="['result-value', 'score', getScoreClass(gameResult.score)]">
                {{ gameResult.score }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="GamePage" lang="ts">
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { showToast } from 'vant';
  import { GameService } from '@/api/services';
  import type { GameContent, GameResult } from '@/api/index';

  const router = useRouter();

  // 响应式数据
  const gameContents = ref<GameContent[]>([]);
  const currentGameIndex = ref(0);
  const currentGame = ref<GameContent | null>(null);
  const isRecording = ref(false);
  const recordStatus = ref('点击开始录音');
  const mediaRecorder = ref<MediaRecorder | null>(null);
  const audioChunks = ref<Blob[]>([]);
  const loading = ref(false);
  const showResult = ref(false);

  // 默认游戏数据
  const defaultGameData: GameContent[] = [
    {
      id: 1,
      standardText: '苹果',
      pinyin: 'píng guǒ',
      image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/3a6233ad9bee355a4f7b19105df580b7.png',
      audioUrl: '',
      level: 'easy',
      category: 'fruit'
    },
    {
      id: 2,
      standardText: '香蕉',
      pinyin: 'xiāng jiāo',
      image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/475a30d46d5cf61b45238bbf0ce85064.png',
      audioUrl: '',
      level: 'easy',
      category: 'fruit'
    },
    {
      id: 3,
      standardText: '蓝天',
      pinyin: 'lán tiān',
      image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/3f343794763632c9ee6a398d93940e87.png',
      audioUrl: '',
      level: 'easy',
      category: 'nature'
    },
  ];

  // 游戏结果 - 初始化默认数据用于调试
  const gameResult = reactive({
    userPronunciation: 'ping guo',
    standardPronunciation: '苹果 (píng guǒ)',
    similarity: 85,
    score: 86,
  });

  // 加载游戏内容
  const loadGameContents = async () => {
    try {
      loading.value = true;
      const data = await GameService.getGameContents();

      if (data && data.length > 0) {
        gameContents.value = data;
        currentGame.value = data[0];
      } else {
        gameContents.value = defaultGameData;
        currentGame.value = defaultGameData[0];
      }
    } catch (error) {
      console.error('加载游戏内容失败:', error);
      gameContents.value = defaultGameData;
      currentGame.value = defaultGameData[0];
    } finally {
      loading.value = false;
    }
  };

  // 返回上一页
  const onClickLeft = () => {
    router.go(-1);
  };

  // 搜索功能
  const handleSearch = () => {
    showToast('搜索功能');
  };

  // 通知功能
  const handleNotification = () => {
    showToast('通知功能');
  };

  // 加载游戏
  const loadGame = () => {
    const gameData = gameContents.value.length > 0 ? gameContents.value : defaultGameData;
    currentGame.value = gameData[currentGameIndex.value];
    showResult.value = false; // 注释掉，保持结果一直显示用于调试
    recordStatus.value = '点击开始录音';
    isRecording.value = false;
  };

  // 切换录音状态
  const toggleRecording = () => {
    if (isRecording.value) {
      stopRecording();
    } else {
      startRecording();
    }
  };

  // 开始录音
  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorder.value = new MediaRecorder(stream);
      audioChunks.value = [];

      mediaRecorder.value.ondataavailable = (event) => {
        audioChunks.value.push(event.data);
      };

      mediaRecorder.value.onstop = () => {
        const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
        sendAudioToBackend(audioBlob);
      };

      mediaRecorder.value.start();
      isRecording.value = true;
      recordStatus.value = '正在录音...点击停止';
      showResult.value = false; // 注释掉，保持结果一直显示用于调试
    } catch (err) {
      console.error('无法获取麦克风权限:', err);
      showToast('无法获取麦克风权限，请检查设置');
    }
  };

  // 停止录音
  const stopRecording = () => {
    if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
      mediaRecorder.value.stop();
      isRecording.value = false;
      recordStatus.value = '录音已停止，正在处理...';
    }
  };

  // 发送音频到后端（模拟）
  const sendAudioToBackend = (audioBlob: Blob) => {
    console.log('发送音频到后端:', audioBlob);

    // 模拟后端处理
    setTimeout(() => {
      const simulatedUserPronunciation = 'ping guo';
      const simulatedSimilarity = Math.random() * 0.3 + 0.7; // 70%-100%相似度
      const calculatedScore = Math.round(simulatedSimilarity * 100);

      gameResult.userPronunciation = simulatedUserPronunciation;
      if (currentGame.value) {
        gameResult.standardPronunciation = `${currentGame.value.standardText} (${currentGame.value.pinyin})`;
      }
      gameResult.similarity = Math.round(simulatedSimilarity * 100);
      gameResult.score = calculatedScore;

      showResult.value = true; // 注释掉，结果一直显示
      recordStatus.value = '点击开始录音';

      // 5秒后切换到下一个游戏
      setTimeout(() => {
        const gameData = gameContents.value.length > 0 ? gameContents.value : defaultGameData;
        currentGameIndex.value = (currentGameIndex.value + 1) % gameData.length;
        loadGame();
      }, 5000);
    }, 2000);
  };

  // 获取分数样式类
  const getScoreClass = (score: number) => {
    if (score >= 80) return 'excellent';
    if (score >= 60) return 'good';
    return 'poor';
  };

  // 组件挂载
  onMounted(async () => {
    await loadGameContents();
    loadGame();
  });

  // 组件卸载
  onUnmounted(() => {
    if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
      mediaRecorder.value.stop();
    }
  });
</script>

<style lang="scss" scoped>
  .game-page {
    background-color: #f5f7fa;
    min-height: 100vh;
    padding-bottom: 20vw; // 为底部导航留空间
  }

  .page-content {
    padding: 4vw;
  }

  .game-section {
    // background: white;
    // border-radius: 4vw;
    padding: 6vw;
    margin-bottom: 6vw;
    // box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .game-title {
    font-size: 5.33vw;
    font-weight: 600;
    color: #1989fa;
    margin-bottom: 6vw;
    text-align: center;
  }

  .game-container {
    width: 100%;
    max-width: 80vw;
    background: #f7f8fa;
    border-radius: 4vw;
    padding: 6vw;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 6vw;

    .game-image-container {
      background: white;
      border-radius: 4vw;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      margin-bottom: 50px;
    }
  }

  .game-image {
    width: 100%;
    height: 48vw;
    margin-bottom: 6vw;
    border-radius: 3vw;
  }

  .game-pinyin {
    font-size: 8vw;
    font-weight: bold;
    color: #1989fa;
    margin-bottom: 6vw;
    text-align: center;
  }

  .record-button {
    width: 20vw;
    height: 20vw;
    border-radius: 50%;
    background: #1989fa;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4vw;
    transition: all 0.3s ease;

    &.recording {
      background: #ee0a24;
      animation: pulse 1.5s infinite;
    }

    .microphone-icon {
      color: white;

      &.recording {
        color: white;
      }
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
      box-shadow: 0 0 0 0 rgba(238, 10, 36, 0.7);
    }
    70% {
      transform: scale(1.05);
      box-shadow: 0 0 0 10px rgba(238, 10, 36, 0);
    }
    100% {
      transform: scale(1);
      box-shadow: 0 0 0 0 rgba(238, 10, 36, 0);
    }
  }

  .record-status {
    font-size: 3.73vw;
    color: #666;
    text-align: center;
  }

  .result-card {
    width: 100%;
    max-width: 80vw;
    margin-top: 4vw;
    background: white;
    border-radius: 4vw;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .result-title {
    font-size: 4.8vw;
    font-weight: 600;
    color: #1989fa;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4vw 6vw 2vw 6vw;
    background: white;
    border-bottom: 1px solid #ebedf0;

    .title-icon {
      margin-right: 2vw;
      font-size: 5.33vw;
    }
  }

  .result-content {
    padding: 4vw 6vw 6vw 6vw;
    background: white;

    .result-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 3vw;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .result-label {
      font-size: 3.73vw;
      color: #666;
    }

    .result-value {
      font-size: 3.73vw;
      font-weight: 500;
      color: #333;

      &.similarity {
        color: #52c41a;
      }

      &.score {
        font-size: 5.33vw;
        font-weight: bold;

        &.excellent {
          color: #52c41a;
        }

        &.good {
          color: #faad14;
        }

        &.poor {
          color: #ff4d4f;
        }
      }
    }
  }

  .ml-4 {
    margin-left: 4vw;
  }
</style>
